﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeTrak.BLL;
using System.Xml.Serialization;
using System.IO;

namespace TimeTrak.DAL
{
    public static class XMLTools
    {
        private const string DIRECTORY = "Data";
        private const string FILE = "Data.xml";

        private static object lock_obj = new object();

        public static void SerializeToXML<T>(T item, string path)
        {
            lock (lock_obj)
            {
                TextWriter textWriter = null;
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    /*since the path is now specified, we dont need to check for dir existance
                     if (!Directory.Exists(DIRECTORY))
                     {
                         Directory.CreateDirectory(DIRECTORY);
                     }
                     textWriter = new StreamWriter(DIRECTORY + @"/" + FILE);
                     */
                    textWriter = new StreamWriter(path);
                    serializer.Serialize(textWriter, item);
                    textWriter.Close();
                }
                catch (Exception ex)
                {
                    if (textWriter != null)
                    {
                        textWriter.Close();
                    }
                    throw new Exception("Error serializing data!", ex);
                }
            }
        }

        public static T DeserializeFromXML<T>(string path)
        {
            T item;
            TextReader textReader = null;
            try
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(T));
                //textReader = new StreamReader(DIRECTORY + @"/" + FILE);
                textReader = new StreamReader(path); 
                item = (T)deserializer.Deserialize(textReader);
                textReader.Close();

            }
            catch (Exception ex)
            {
                if (textReader != null)
                {
                    textReader.Close();
                }
                throw new Exception("Error deserializing data!", ex);
            }

            return item;

        }

    }
}
